﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

namespace ProgNetComponents.Wcf.AppUpdate
{
    public class XmlUpdateHolder
    {
        public DataTable Table { get; private set; }

        private string File { get; set; }

        public XmlUpdateHolder(string file)
        {
            File = file;
            try
            {
                string dir = Path.GetDirectoryName(File);
                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);
            }
            catch { }

            Table = new DataTable("Updates");
            Table.Columns.AddRange("Version", "File", "Changelog");
            try
            {
                Table.ReadXml(File);
            }
            catch { }
        }

        public void AddOrUpdateVersion(AppVersionInfo info)
        {
            DataRow r = Table.SelectFirstRow("Version = " + info.Host.ToString().EscapeSql());
            if (r == null)
            {
                r = Table.NewRow();
                r["Version"] = info.Host.ToString();
                Table.Rows.Add(r);
            }
            r["File"] = info.File;
            r["Changelog"] = info.Changelog;
            Save();
        }
        
        public bool Save()
        {
            bool result = false;
            try
            {
                Table.AcceptChanges();
                Table.WriteXml(File);
                result = true;
            }
            catch { }
            return result;
        }
    }
}
